package cn.edu.sdjzu.xg.bysj.service;

import cn.edu.sdjzu.xg.bysj.dao.SchoolDao;
import cn.edu.sdjzu.xg.bysj.domain.Condition;
import cn.edu.sdjzu.xg.bysj.domain.Department;
import cn.edu.sdjzu.xg.bysj.domain.Pagination;
import cn.edu.sdjzu.xg.bysj.domain.School;
import cn.edu.sdjzu.xg.bysj.exception.BysjException;
import cn.edu.sdjzu.xg.bysj.util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public class SchoolService {
    private SchoolService(){}
    private School school = null;
    private Collection<School> schools = null;
    private static SchoolService schoolService = null;
    public static SchoolService getInstance() throws SQLException {
        if(schoolService == null){
            schoolService = new SchoolService();
        }
        return schoolService;
    }

    public School find(Integer id) throws SQLException, BysjException {
        return SchoolDao.getInstance().find(id);
    }

    public Collection<School> findAll(List<Condition> conditionList) throws SQLException,BysjException {
        return SchoolDao.getInstance().findAll(conditionList);
    }

    public Collection<School> findAll(List<Condition> conditionList, Pagination pagination) throws SQLException, BysjException {
        return SchoolDao.getInstance().findAll(conditionList,pagination);
    }

    public boolean delete(int id) throws SQLException,BysjException{
        boolean canBeDeleted = true;
        Collection<Department> departments = DepartmentService.getInstance().findAll();
        for (Department department:departments){
            // 每一次循环，如果遍历到的当前专业的school的id等于参数id，那么 canBeDeleted = false。如果不等于则什么都不发生，进入下一次循环
            if (department.getSchool().getId() == id){
                canBeDeleted = false;
                // 只要检测到学院下的一个专业即可，剩下的专业无需再遍历，用break跳出循环，减少运行时间
                break;
            }
        }
        if (canBeDeleted){
            SchoolDao.getInstance().delete(id);
        }
        return canBeDeleted;
    }
    public boolean add(School school)throws SQLException, BysjException {
        Connection connection = JdbcHelper.getConn();
        boolean added = SchoolDao.getInstance().add(connection,school);
        JdbcHelper.close(connection);
        return added;
    }
    public boolean update(School school)throws SQLException , BysjException {
        Connection connection = JdbcHelper.getConn();
        boolean added = SchoolDao.getInstance().update(connection,school);
        JdbcHelper.close(connection);
        return added;
    }
}